<template>
  <BasicModal v-bind="$attrs" @register="registerApplyModal" :defaultFullscreen="true" destroyOnClose :title="applyModa.title" @ok="handleSubmit">
    <component
      :formDisabled="applyModa.disabled"
      :formData="{ disabled: applyModa.disabled, tableId: applyModa.tableId,tableData:applyModa.tableData }"
      v-if="applyModa.visible"
      :is="applyModa.formComponent"
      :processData="applyModa.processData"
      :isNew="applyModa.isNew"
      :withStore="applyModa.withStore"
      @close="handleClose"
      @ok="handleOk"
      ref="registerForm"
    />
    <GateWayModal @register="registerGwModal" @success="handleGwSuccess" />
    <template v-if="applyModa.dataSet" #centerFooter>
      <a-button type="primary" @click="handleSave(applyModa.isNew)">保存</a-button>
    </template>

  </BasicModal>
</template>

<script lang="ts" setup>
  import {ref, computed, unref, reactive, shallowRef, defineAsyncComponent} from 'vue';
  import {BasicModal, useModal, useModalInner} from '/@/components/Modal';
  import {isArray,isEmpty} from "@/utils/is";
  import GateWayModal from '/@/components/ApplyModal/GateWay.vue'
  import {useMessage} from "@/hooks/web/useMessage";
  import {getProcessDataList} from "@/views/activiti/modules/ActReModel.api";

  const [registerGwModal, {openModal}] = useModal();

   const {createMessage} = useMessage()
   const registerForm = ref();
    const applyModa = reactive({
      title: '审批',
      disabled: false,
      visible: false,
      formComponent: <any>null,
      dataSet:false, //是否由保存数据按钮显示
      isNew: false, //新增还是编辑数据
      withStore:false,//审批时候附带保存数据
      tableId: null,  //数据表id
      processData:null, //流程数据
      tableData:null,
      productTitle:null  //带过来的标题
    });
    // Emits声明
    const emit = defineEmits(['register','success']);
    const withApply = ref(true)

    //表单赋值`
    const [registerApplyModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
        setModalProps({confirmLoading: true});
        const record = data.record
        withApply.value = !!data.withApply
        if (!data.applyKey){
          createMessage.error("发生错误了,缺少流程标识!")
          return
        }
        const curFlow = await findApplyFlow(data.applyKey)
        if (!curFlow||!curFlow.routeName){
          createMessage.error("没有找到审批流程!")
          setModalProps({confirmLoading: false});
          return
        }
        const modules:any = import.meta.glob(['/src/views/**/*.vue'])
        applyModa.disabled=!!data.formDisable
        applyModa.dataSet = !!data.dateSet
        applyModa.isNew = !!data.isNew
        applyModa.withStore = !!data.withStore
        applyModa.tableId = record?record.id:null;
        applyModa.processData = curFlow
        applyModa.tableData = record
        applyModa.productTitle = data.title
        applyModa.formComponent = shallowRef(defineAsyncComponent(modules[`/src/views/${curFlow.routeName}.vue`]));
        applyModa.title = curFlow?'发起流程：'+curFlow.name:data.title
        applyModa.visible = true;

        setModalProps({confirmLoading: false,showCancelBtn:!!data?.showFooter,showOkBtn:!!data?.showFooter&&withApply.value,cancelText:'关闭',okText:'提交审批'});

    });

    async function findApplyFlow(applyKey){
      const result = await getProcessDataList({ status: 1, roles: true })
      if (isArray(result)){
        return result.find(flow=>flow.processKey==applyKey)
      }
      return null
    }

    //表单事件回调
    function handleOk(){
      console.log("ok")
    }
    //表单事件回调
    function handleClose(){
      console.log("close")
      applyModa.visible = false
      applyModa.disabled = false
    }

    //表单提交事件
    async function handleSubmit(v) {
        try {
            setModalProps({confirmLoading: true});
            //关闭弹窗
            registerForm.value.submitForm((res)=>{
              handleFormResult(res)
            });
            //刷新列表

        } finally {
            setModalProps({confirmLoading: false});
        }
    }

    //数据保存/修改提交
    function handleSave(isNew){
      try {
          setModalProps({confirmLoading: true});
          //关闭弹窗
          registerForm.value.saveForm((res)=>{
            createMessage.success("保存成功!")
            applyModa.isNew=false
            if (!withApply.value){
              closeModal()
              emit('success')
            }

          });
          //刷新列表

      } finally {
          setModalProps({confirmLoading: false});
      }

    }

    //审批提交
    function handleFormResult(res){
      const formdata = {
        //此处title用于审批标题拼接
        title:applyModa.productTitle?applyModa.productTitle:'',
        procDefId: applyModa.processData?.id,
        procDeTitle: applyModa.processData?.name,
        processKey:applyModa.processData?.processKey,
        tableName: applyModa.processData?.businessTable,
        name: applyModa.processData?.name,
        tableId: res.id
      }
      openModal(true,{
        record:formdata
      })
    }



    function handleGwSuccess(){
      closeModal()
      emit('success');
    }
</script>

<style lang="less" scoped>
	/** 时间和数字输入框样式 */
  :deep(.ant-input-number){
		width: 100%
	}

	:deep(.ant-calendar-picker){
		width: 100%
	}
</style>
